/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'dart:async';

import 'package:flutter/widgets.dart';

import 'folder_plugin.dart';
import 'folder_options.dart';

///FolderStack继承于Stack(层叠布局)控件，新增了折叠屏悬停能力，通过识别upperItems自动避让折叠屏折痕区后移到上半屏
class FolderStack extends StatefulWidget {
  const FolderStack({
    super.key,
    required this.upperItems,
    required this.children,
    this.onFolderStateChange,
    this.verticalDirection = VerticalDirection.down,
    this.alignment = AlignmentDirectional.topStart,
    this.textDirection,
    this.fit = StackFit.loose,
    this.clipBehavior = Clip.hardEdge,
  });

  ///定义悬停态会被移到上半屏的子组件的id，组件id在此数组中的子组件悬停触发时自动避让折叠屏折痕区后移到上半屏，其它组件堆叠在下半屏区域。
  final List<String> upperItems;

  ///当折叠状态改变的时候回调
  final ValueChanged<FoldStatus>? onFolderStateChange;

  /// Same as [MultiChildRenderObjectWidget.children].
  final List<Widget> children;

  /// Same as [Stack.alignment].
  ///    relative to text direction.
  final AlignmentGeometry alignment;

  /// Same as [Stack.textDirection].
  /// Defaults to the ambient [Directionality].
  final TextDirection? textDirection;

  /// Same as [Stack.fit].
  /// ([StackFit.expand]).
  final StackFit fit;

  /// Same as [Stack.clipBehavior].
  /// Defaults to [Clip.hardEdge].
  final Clip clipBehavior;

  /// Same as [Flex.verticalDirection].
  ///
  /// Defaults to [VerticalDirection.down].
  final VerticalDirection verticalDirection;

  @override
  State<StatefulWidget> createState() {
    return _FolderStackState();
  }
}

class _FolderStackState extends State<FolderStack> {
  late StreamSubscription<FoldingFeature> _subscription;
  var foldingFeature = FoldingFeature();

  @override
  void initState() {
    super.initState();
    _subscription =
        FolderStackPlugin.folderStateEvents.listen((FoldingFeature status) {
      if (status.state != foldingFeature.state ||
          status.orientation != foldingFeature.orientation) {
        setState(() {
          foldingFeature = status;
        });
        widget.onFolderStateChange?.call(foldingFeature.state);
      }
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final MediaQueryData? mediaQuery = MediaQuery.maybeOf(context);
    late int startPaneFlex;
    late int endPaneFlex;

    if (foldingFeature.state != FoldStatus.halfFolded ||
        foldingFeature.orientation == Axis.vertical ||
        mediaQuery == null) {
      return _createStack(widget.children);
    }

    List<Widget> upperStackChildren = [];
    List<Widget> lowerStackChildren = [];

    for (var child in widget.children) {
      if (child is Container &&
          (child.key is ValueKey) &&
          widget.upperItems.contains((child.key as ValueKey<String>).value)) {
        upperStackChildren.add(child);
      } else {
        lowerStackChildren.add(child);
      }
    }

    final topStack = _createStack(upperStackChildren);
    final lowerStack = _createStack(lowerStackChildren);

    // 获取屏幕大小
    Size screenSize = mediaQuery.size;
    // 将 Android 像素值转换为逻辑像素
    Rect foldBounds = Rect.fromLTRB(
      foldingFeature.bounds.left / mediaQuery.devicePixelRatio,
      foldingFeature.bounds.top / mediaQuery.devicePixelRatio,
      foldingFeature.bounds.right / mediaQuery.devicePixelRatio,
      foldingFeature.bounds.bottom / mediaQuery.devicePixelRatio,
    );

    // 确保折叠屏痕迹在屏幕内
    if (foldBounds.top > screenSize.height) {
      // 如果折叠屏痕迹在屏幕之外，可以调整为屏幕中间或其他位置
      foldBounds = Rect.fromLTWH(0, screenSize.height / 2, screenSize.width, 1);
    }

    // 计算每个区域的高度
    double aboveFoldHeight = foldBounds.top;
    double belowFoldHeight = screenSize.height - foldBounds.bottom;

    // 计算 flex 值
    startPaneFlex = (aboveFoldHeight / screenSize.height * 100).round();
    endPaneFlex = (belowFoldHeight / screenSize.height * 100).round();

    // 确保 flex 值至少为 1
    startPaneFlex = startPaneFlex > 0 ? startPaneFlex : 1;
    endPaneFlex = endPaneFlex > 0 ? endPaneFlex : 1;

    return Flex(
      direction: Axis.vertical,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      verticalDirection: widget.verticalDirection,
      children: <Widget>[
        Expanded(
          flex: startPaneFlex,
          child: topStack,
        ),
        SizedBox(
          height: foldBounds.height,
          width: foldBounds.width,
        ),
        Expanded(
          flex: endPaneFlex,
          child: lowerStack,
        ),
      ],
    );
  }

  // 创建Stack
  Stack _createStack(List<Widget> children) {
    return Stack(
      fit: widget.fit,
      alignment: widget.alignment,
      textDirection: widget.textDirection,
      clipBehavior: widget.clipBehavior,
      children: children,
    );
  }
}
